package com.android.lovely.ui.dialog
import androidx.core.view.isVisible
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import com.android.lovely.R
import com.android.lovely.const.HomeShowTask
import com.android.lovely.const.UpLoadStep
import com.android.lovely.databinding.DialogSubmitLoadBinding
import com.android.lovely.framework.BaseDialogFragment
import com.android.lovely.ui.viewmodel.CreateRolePreviewViewModel
import com.android.lovely.ui.viewmodel.CreateRoleViewModel
import com.kotlin.extensions.bus.FlowBus
import com.kotlin.extensions.bus.flowOf
import com.kotlin.extensions.bus.post
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 *
 * @author why
 * @date 2025/4/8 22:34
 */

// 定义上传状态的策略接口
interface UploadStatusStrategy {
    fun execute()
}

// 头像上传策略
class AvatarUploadStrategy(private val dialog: UpLoadDialog) : UploadStatusStrategy {
    override fun execute() {
        dialog.binding.count.isVisible = false
        dialog.binding.tip.text = dialog.getString(R.string.uploading_avatar)
    }
}

// 图片上传策略
class PhotoUploadStrategy(private val dialog: UpLoadDialog, private val photoIndex: Int) : UploadStatusStrategy {
    override fun execute() {
        dialog.binding.count.isVisible = true
        dialog.binding.tip.text = dialog.getString(R.string.uploading_please_be_patient)
        dialog.binding.count.text = "${photoIndex}/${dialog.cardNum}"
    }
}

// 创建机器人策略
class CreatingBotStrategy(private val dialog: UpLoadDialog) : UploadStatusStrategy {
    override fun execute() {
        dialog.binding.count.isVisible = false
        dialog.binding.tip.text = dialog.getString(R.string.create_new_role)
    }
}

class UpLoadDialog : BaseDialogFragment<DialogSubmitLoadBinding>() {

    private val createRolePreviewViewModel by activityViewModels<CreateRolePreviewViewModel> ()

    private val createRoleViewModel by activityViewModels<CreateRoleViewModel> ()
    private var isQuick = false

    val cardNum by lazy { if (isQuick) createRolePreviewViewModel.createRole?.cards?.size ?: 0
    else createRoleViewModel.createRole?.cards?.size ?: 0 }

    override fun initializeViews() {
        isCancelable = false
//        val id = arguments?.getInt("role_id", SystemClock.elapsedRealtime().toInt()) ?:SystemClock.elapsedRealtime().toInt()
        isQuick =  arguments?.getBoolean("isEdit") ?: false

        lifecycleScope.launch {
            FlowBus.flowOf<UpLoadStep>().collect {
                val strategy = when (it.step) {
                    -1 -> AvatarUploadStrategy(this@UpLoadDialog)
                    cardNum -> CreatingBotStrategy(this@UpLoadDialog)
                    else -> PhotoUploadStrategy(this@UpLoadDialog, it.step)
                }
                strategy.execute()
            }
        }
    }
}